package com.example.mongodb.mongodb.controller.rabbitmq.workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Work {


    public static void main(String[] args) {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("123.207.179.78");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        Connection connection = null;

        //自动确认消息
        boolean autoAck = true;
        try {
            connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();

            //预取指定个数的消息
//            channel.basicQos(1);


            DeliverCallback deliverCallback = (consumerTag,delivery)->{
                String task = new String(delivery.getBody(),"UTF-8");
                System.out.println("[x] Received "+task);
                for(char ch: task.toCharArray()){
                    if(ch == '.') {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }finally {
                            //手动确认消息
//                            channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                        }
                    }
                }
            };

            channel.queueDeclare("taskQueue",false,false,false,null);

            channel.basicConsume("taskQueue",autoAck,deliverCallback,consumerTag->{});


        }  catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
